package com.medical.controller;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.medical.HttpTools.DataAnalyze;
import com.medical.HttpTools.HttpRequest;
import com.medical.po.DoctorinfoCustom;
import com.medical.po.Hospinfo;
import com.medical.po.HospinfoCustom;
import com.medical.po.Hospitaldept;
import com.medical.po.HospitaldeptCustom;
import com.medical.po.HosplogininfoCustom;
import com.medical.service.DoctorinfoService;
import com.medical.service.HospinfoService;
import com.medical.service.HospitaldeptService;
import com.medical.service.HosplogininfoService;
@Controller
@RequestMapping(value="/Main/myinfo")
/**
 * 
 * @author LTT-AH-ZY
 * @date 创建时间：2017年7月24日 下午5:07:42 
 * @version 1.0
 * @parameter 参数及其意义
 * @return 返回值
 * @throws 异常类及抛出条件
 */
public class MyInforController {
	/**
	 * 注入多服务：HosplogininfoService，HospinfoService，HospitaldeptService，DoctorinfoService
	 */
	@Autowired
	private HosplogininfoService hosplogininfoService ;
	@Autowired
	private HospinfoService hospinfoService;
	@Autowired
	private HospitaldeptService  hospitaldeptService;
	@Autowired
	private DoctorinfoService doctorinfoService ;
	/**
	 * 我的基本登陆信息和我的医院详细信息的view展示
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/MyInformation")
	public ModelAndView MyInformation(HttpServletRequest request,ModelAndView model) throws Exception{
		HttpSession session=request.getSession();
		Integer hosploginid = (Integer)session.getAttribute("hosploginid");
		Map<String,Object> logininfolist = new HashMap<>();
		Map<String,Object> infolist = new HashMap<>();
		try {
			JSONObject logininfojson = HttpRequest.sendPost("/getlogininfo","hosploginid="+hosploginid);
			System.out.println("输出这个logininfojson:"+logininfojson);
			String jsoncode = logininfojson.get("code").toString();
			String msg = logininfojson.get("msg").toString();
			if("100".equals(jsoncode)) {
				JSONObject datajson = logininfojson.getJSONObject("data");
				logininfolist.put("hosploginphone", datajson.get("hosploginphone").toString());
				logininfolist.put("hosplogintype", datajson.get("hosplogintype").toString());
				logininfolist.put("hosplogintypename", datajson.get("hosplogintypename").toString());
				logininfolist.put("hosplogintime", datajson.get("hosplogintime").toString());
				logininfolist.put("hosploginpix", datajson.get("hosploginpix").toString());
				logininfolist.put("examineideas", datajson.get("examineideas").toString());
			}
		} catch (Exception e) {
			System.out.println("1出错了，出错信息是："+e.getMessage());
		}
		try {
			JSONObject infojson = HttpRequest.sendPost("/getinfo", "hosploginid="+hosploginid);
			System.out.println("输出这个infojson:"+infojson);
			String jsoncode = infojson.get("code").toString();
			String jsonmsg = infojson.get("msg").toString();
			if ("100".equals(jsoncode)) {
				JSONObject datajson = infojson.getJSONObject("data");
				infolist.put("hospname", datajson.get("hospname").toString());
				infolist.put("hospgrade", datajson.get("hospgrade").toString());
				infolist.put("hospadrprovince", datajson.get("hospadrprovince").toString());
				infolist.put("hospadrcity", datajson.get("hospadrcity").toString());
				infolist.put("hospadrarea", datajson.get("hospadrarea").toString());
				infolist.put("hospadrother", datajson.get("hospadrother").toString());
				infolist.put("hospphone", datajson.get("hospphone").toString());
				infolist.put("hospfeature", datajson.get("hospfeature").toString());
				infolist.put("hospabs", datajson.get("hospabs").toString());
				infolist.put("hospregidcard", datajson.get("hospregidcard").toString());
				if(datajson.get("hosppraclicense").toString()!="") {
					String[] hosppraclicense=datajson.get("hosppraclicense").toString().split(",");
					infolist.put("hosppraclicense0", hosppraclicense[0].toString());
					try {
						infolist.put("hosppraclicense1", hosppraclicense[1].toString());
					} catch (Exception e) {
						infolist.put("hosppraclicense1", "");
					}
				}else {
					infolist.put("hosppraclicense0", "");
					infolist.put("hosppraclicense1", "");
				}
				if(datajson.get("hospregdocquacer").toString()!="") {
					String[] hospregdocquacer=datajson.get("hospregdocquacer").toString().split(",");
					infolist.put("hospregdocquacer0", hospregdocquacer[0].toString());
					try {
						infolist.put("hospregdocquacer1", hospregdocquacer[1].toString());
					} catch (Exception e) {
						infolist.put("hospregdocquacer1", "");
					}
				}else {
					infolist.put("hospregdocquacer0", "");
					infolist.put("hospregdocquacer1", "");
				}
				if(datajson.get("hosporgcodecer").toString()!="") {
					String[] hosporgcodecer=datajson.get("hosporgcodecer").toString().split(",");
					infolist.put("hosporgcodecer0", hosporgcodecer[0].toString());
					try {
						infolist.put("hosporgcodecer1", hosporgcodecer[1].toString());
					} catch (Exception e) {
						infolist.put("hosporgcodecer1", "");
					}
				}else {
					infolist.put("hosporgcodecer0", "");
					infolist.put("hosporgcodecer1", "");
				}
				if(datajson.get("hosplegalcer").toString()!="") {
					String[] hosplegalcer=datajson.get("hosplegalcer").toString().split(",");
					infolist.put("hosplegalcer0", hosplegalcer[0].toString());
					try {
						infolist.put("hosplegalcer1", hosplegalcer[1].toString());
					} catch (Exception e) {
						infolist.put("hosplegalcer1", "");
					}
				}else {
					infolist.put("hosplegalcer0", "");
					infolist.put("hosplegalcer1", "");
				}
			}
		} catch (Exception e) {
			System.out.println("2出错了，出错信息是："+e.getMessage());
		}
		model.addObject("logininfolist", logininfolist);
		model.addObject("infolist", infolist);
		model.setViewName("MainFrame/MyInformation/MyInformation");
		return model;
	}
	/**
	 * 初始化完善医院信息的view
	 * @return
	 */
	/*@RequestMapping(value="/MyInfoReg")
	public String MyInfoReg(){
		return "MainFrame/MyInformation/MyInfoReg";
	}*/
	/**
	 * 完善医院信息的提交Handler，接收照片信息和
	 * @param hospinfo
	 * @param response
	 * @param certify_pic
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/MyInfoRegSubmit")
	public String MyInfoRegSubmit(Hospinfo hospinfo,HttpServletResponse response,@RequestParam("certify_pic") MultipartFile[] certify_pic,ModelAndView model,HttpSession session) throws Exception{
		System.out.println("输出的医院名称等信息是："+hospinfo.getHospname());
		//将session中值写入hospinfo中，等后面统一处理
		Integer hosploginid = (Integer)session.getAttribute("hosploginid");
		hospinfo.setHosploginid(hosploginid);
		//原始名称
		String originalRegdocquacer = certify_pic[0].getOriginalFilename();//注册医师资格证照片
		String originalOrgcodecer = certify_pic[1].getOriginalFilename();//医院代码证
		String originalPraclicense = certify_pic[2].getOriginalFilename();//注册医院执业许可证
		String originalLegalcer = certify_pic[3].getOriginalFilename();//注册医院法人证明照片
		if(certify_pic!=null && originalRegdocquacer!=null && originalOrgcodecer!=null && originalPraclicense!=null && originalLegalcer!=null && originalRegdocquacer.length()>0 && originalOrgcodecer.length()>0 && originalPraclicense.length()>0 && originalLegalcer.length()>0) {
			//存储图片的物理路径
			String pic_path = "E:\\upload\\temp\\";
			//新的图片名称
			String newFileRegdocquacer = UUID.randomUUID() + originalRegdocquacer.substring(originalRegdocquacer.lastIndexOf("."));
			String newFileOrgcodecer = UUID.randomUUID() + originalOrgcodecer.substring(originalOrgcodecer.lastIndexOf("."));
			String newFilePraclicense = UUID.randomUUID() + originalPraclicense.substring(originalPraclicense.lastIndexOf("."));
			String newFileLegalcer = UUID.randomUUID() + originalLegalcer.substring(originalLegalcer.lastIndexOf("."));
			//新图片
			File newRegdocquacer = new File(pic_path+newFileRegdocquacer);
			File newOrgcodecer = new File(pic_path+newFileOrgcodecer);
			File newPraclicense = new File(pic_path+newFilePraclicense);
			File newLegalcer = new File(pic_path+newFileLegalcer);
			//将内存中的数据写入磁盘
			certify_pic[0].transferTo(newRegdocquacer);
			certify_pic[1].transferTo(newOrgcodecer);
			certify_pic[2].transferTo(newPraclicense);
			certify_pic[3].transferTo(newLegalcer);
			//将图片名称写到hospinfo中去，最后统一执行insert方法
			hospinfo.setHospregdocquacer(newFileRegdocquacer);
			hospinfo.setHosporgcodecer(newFileOrgcodecer);
			hospinfo.setHosppraclicense(newFilePraclicense);
			hospinfo.setHosplegalcer(newFileLegalcer);
			
			System.out.println("成功执行写入磁盘操作！！！");
			System.out.println("输出新的图片名称："+newFileRegdocquacer+"////"+newOrgcodecer+"////"+newPraclicense+"////"+newLegalcer);
		}
		System.out.println("输出上传的几张照片旧名称："+originalRegdocquacer+"////"+originalOrgcodecer+"////"+originalPraclicense+"////"+originalLegalcer);
		int result = hospinfoService.insertHosp(hospinfo);
		/*System.out.println("输出的医院名称等信息是："+hospinfo.getHospadr());
		System.out.println("输出的医院名称等信息是："+hospinfo.getHospphone());
		System.out.println("输出的医院名称等信息是："+hospinfo.getHospabs());
		System.out.println("输出的医院名称等信息是："+hospinfo.getHospgrade());
		System.out.println("输出的医院名称等信息是："+hospinfo.getHospfeature());
		System.out.println("输出的医院名称等信息是："+hospinfo.getHosporgcodecer());*/
		if(result==1) {
			model.addObject("message", "资料上传成功，不要重复提交，等待管理员审核！");
		}else {
			model.addObject("message", "资料上传失败，点这里重新填写，勿刷新页面，防止多次提交系统报错！！");
		}
		return "MainFrame/MyInformation/MyInfoReg";
	}
	/**
	 * 我的医生管理界面初始化
	 * @return
	 */
	/*@RequestMapping(value="/mydoctorman")
	public ModelAndView MyDoctorMan() {
		ModelAndView model = new ModelAndView();
		model.setViewName("/MainFrame/MyInformation/MyDoctorMan");
		return model;
	}*/
	/**
	 * 我的医院部门信息初始化查询
	 * @return
	 * @throws Exception
	 */
	/*@RequestMapping(value="/mydoctormanCheck")
	public @ResponseBody List<HospitaldeptCustom> mydoctormanCheck(HttpSession session,HospitaldeptCustom hospitaldeptCustom) throws Exception {
		Integer hospid = (Integer)session.getAttribute("hospid");
		hospitaldeptCustom.setHospid(hospid);
		List<HospitaldeptCustom> backhospitaldeptCustom = hospitaldeptService.findHospitaldeptList(hospitaldeptCustom);
		System.out.println("成功");
		return backhospitaldeptCustom;
	}*/
	/**
	 * 部门信息查询，select by id
	 * @param hospitaldept
	 * @return
	 * @throws Exception
	 */
	/*@RequestMapping(value="/hospitaldeptShow")
	public @ResponseBody Hospitaldept hospitaldeptShow(@RequestBody Hospitaldept hospitaldept) throws Exception{
		//System.out.println("输出传参数"+hospitaldept.getHospdeptid());
		Hospitaldept hospitaldeptabs = hospitaldeptService.findHospitalDeptAbs(hospitaldept.getHospdeptid());
		//System.out.println("输出查询到的数据是"+hospitaldeptabs);
		return hospitaldeptabs;
	}*/
	/**
	 * 医院各个部门的医生查询初始化，该功能阉割了。。。
	 * @param doctorinfoCustom
	 * @return
	 * @throws Exception
	 */
	/*@RequestMapping(value="/hospdeptdoctors")
	public @ResponseBody List<DoctorinfoCustom> hospdeptdoctors(@RequestBody DoctorinfoCustom doctorinfoCustom) throws Exception{
		System.out.println("输出doctors的参数是"+doctorinfoCustom.getDocdept());
		List<DoctorinfoCustom> doctorinfoCustom2 = doctorinfoService.findDoctorList(doctorinfoCustom);
		System.out.println("test");
		return doctorinfoCustom2;
	}*/
	/**
	 * 交易记录表界面初始化
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/TradeRecordList")
	public ModelAndView TradeRecordList()throws Exception{
		ModelAndView model = new ModelAndView();
		model.setViewName("MainFrame/MyInformation/TradeRecordList");
		return model;
	}
	/**
	 * 交易记录表的ajax异步加载类
	 * @param limit
	 * @param offset
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/listtraderecord")
	public @ResponseBody Map<String,Object> listtraderecord(Integer limit,Integer offset,HttpServletRequest request)throws Exception{
		HttpSession session = request.getSession();
		Integer hosploginid = (Integer)session.getAttribute("hosploginid");
		String param = "hosploginid="+hosploginid+"&limit="+limit+"&offset="+offset;
		
		Map<String,Object> result = new HashMap<String,Object>();
		String jsonmsg = "";
		String jsoncode ="";
		Integer total=0;
		List<Map<String,Object>> traderecordlist=null;
		try {
			JSONObject json = HttpRequest.sendPost("listtraderecord", param);
			jsoncode = json.get("code").toString();
			jsonmsg = json.get("msg").toString();
			
			try {
				if(json.get("data").toString()!="null") {
					JSONObject jsonobjectdata =json.getJSONObject("data");
					JSONArray jsonarrayrows = jsonobjectdata.getJSONArray("rows");
					total = Integer.parseInt(jsonobjectdata.get("total").toString());
					traderecordlist = DataAnalyze.TraderecordJsonToList(jsonarrayrows);
				}
			} catch (Exception e) {
				System.out.println("出错了，出错信息是："+e.getMessage());
			}
		} catch (Exception e) {
			System.out.println("出错了，出错信息是："+e.getMessage());
		}
		result.put("msg", jsonmsg);
		result.put("code", jsoncode);
		result.put("rows", traderecordlist);
		result.put("total", total);
		
		System.out.println("输出这个result是："+result);
		return result;
	}
	/**
	 * 余额变动记录列表界面初始化
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/BalanceRecordList")
	public ModelAndView BalanceRecordList()throws Exception{
		ModelAndView model = new ModelAndView();
		model.setViewName("MainFrame/MyInformation/BalanceRecordList");
		return model;
	}
	/**
	 * 余额变动记录列表的ajax异步加载类
	 * @param limit
	 * @param offset
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/listbalancerecord")
	public @ResponseBody Map<String,Object> listbalancerecord(Integer limit,Integer offset,HttpServletRequest request)throws Exception{
		HttpSession session = request.getSession();
		Integer hosploginid = (Integer)session.getAttribute("hosploginid");
		String param = "hosploginid="+hosploginid+"&limit="+limit+"&offset="+offset;
		
		Map<String,Object> result = new HashMap<String,Object>();
		String jsonmsg = "";
		String jsoncode ="";
		Integer total=0;
		List<Map<String,Object>> balancerecordlist=null;
		try {
			JSONObject json = HttpRequest.sendPost("listbalancerecord", param);
			jsoncode = json.get("code").toString();
			jsonmsg = json.get("msg").toString();
			
			try {
				if(json.get("data").toString()!="null") {
					JSONObject jsonobjectdata =json.getJSONObject("data");
					JSONArray jsonarrayrows = jsonobjectdata.getJSONArray("rows");
					total = Integer.parseInt(jsonobjectdata.get("total").toString());
					balancerecordlist = DataAnalyze.BalancerecordJsonToList(jsonarrayrows);
				}
			} catch (Exception e) {
				System.out.println("出错了，出错信息是："+e.getMessage());
			}
		} catch (Exception e) {
			System.out.println("出错了，出错信息是："+e.getMessage());
		}
		result.put("msg", jsonmsg);
		result.put("code", jsoncode);
		result.put("rows", balancerecordlist);
		result.put("total", total);
		
		System.out.println("输出这个result是："+result);
		return result;
	}
	/**
	 * 获取当前账户余额
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getBalance")
	public @ResponseBody Map<String,Object> getBalance(HttpServletRequest request)throws Exception{
		HttpSession session = request.getSession();
		Integer hosploginid = (Integer)session.getAttribute("hosploginid");
		String param = "hosploginid="+hosploginid;
		Map<String,Object> result = new HashMap<>();
		String jsoncode = "";
		String jsonmsg = "";
		double balance=0.00;
		try {
			JSONObject json = HttpRequest.sendPost("getbalance", param);
			jsoncode = json.get("code").toString();
			jsonmsg = json.get("msg").toString();
			try {
				if(json.get("data").toString()!="null") {
					balance = Double.parseDouble(json.get("data").toString());
				}
			} catch (Exception e) {
				System.out.println("出错了，错误信息是："+e.getMessage());
			}
		} catch (Exception e) {
			System.out.println("出错了，错误信息是："+e.getMessage());
		}
		result.put("code", jsoncode);
		result.put("msg", jsonmsg);
		result.put("balance", balance);
		
		return result;
	}
	/**
	 * 获取账户的支付宝账号
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getAlipayaccount")
	public @ResponseBody Map<String,Object> getAlipayaccount(HttpServletRequest request)throws Exception{
		HttpSession session = request.getSession();
		Integer hosploginid = (Integer)session.getAttribute("hosploginid");
		String param = "hosploginid="+hosploginid;
		Map<String,Object> result = new HashMap<>();
		String jsoncode = "";
		String jsonmsg = "";
		String alipayaccount="";
		String alipayname="";
		try {
			JSONObject json = HttpRequest.sendPost("getalipayaccount", param);
			jsoncode = json.get("code").toString();
			jsonmsg = json.get("msg").toString();
			try {
				if(json.get("data").toString()!="null") {
					JSONObject jsondata=json.getJSONObject("data");
					alipayaccount = jsondata.get("alipayaccount").toString();
					alipayname=jsondata.get("alipayname").toString();
				}
			} catch (Exception e) {
				System.out.println("出错了，错误信息是："+e.getMessage());
			}
		} catch (Exception e) {
			System.out.println("出错了，错误信息是："+e.getMessage());
		}
		result.put("code", jsoncode);
		result.put("msg", jsonmsg);
		result.put("alipayaccount", alipayaccount);
		result.put("alipayname", alipayname);
		return result;
	}
	/**
	 * 绑定或修改支付宝账号
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/Updatealipayaccount")
	public @ResponseBody Map<String,Object> Updatealipayaccount(HttpServletRequest request)throws Exception{
		HttpSession session = request.getSession();
		Integer hosploginid= (Integer)session.getAttribute("hosploginid");
		String alipayaccount = request.getParameter("alipayaccount");
		String alipayname= request.getParameter("alipayname");
		String param = "hosploginid="+hosploginid+"&alipayaccount="+alipayaccount+"&alipayname="+alipayname;
		Map<String,Object> result = new HashMap<>();
		
		String jsoncode="";
		String jsonmsg="";
		try {
			JSONObject json = HttpRequest.sendPost("updatealipayaccount", param);
			jsoncode = json.get("code").toString();
			jsonmsg = json.get("msg").toString();
		} catch (Exception e) {
			jsoncode="-100";
			jsonmsg="数据连接出错！";
			System.out.println("出错了，错误信息是："+e.getMessage());
		}
		result.put("code", jsoncode);
		result.put("msg", jsonmsg);
		return result;
	}
}
